package com.winkyle.woodenfish.util;

import android.content.Context;
import android.util.Log;

import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import java.io.IOException;
import java.nio.charset.Charset;

import okio.Buffer;
import okio.BufferedSource;

/**
 * @author winkyle
 * @date 2018/06/19
 * @description cookie拦截器(用于请求之后拦截)
 */

public class CookiesSavaInterceptor implements Interceptor {
    private String TAG = "CookiesSavaInterceptor";
    private Context context;

    public CookiesSavaInterceptor(Context context) {
        this.context = context;
    }

    /**
     * @description 拦截cookie将其保存到本地
     * @param chain
     * @return
     * @throws IOException
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        //打印网络返回数据，不可用responseBody.string，调用一次之后就关闭流，后报错
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset UTF8 = Charset.forName("UTF-8");
        Log.d(TAG, buffer.clone().readString(UTF8));

        //将cookie存入本地
        if (!response.headers("Set-Cookie").isEmpty()) {
            Log.d(TAG,buffer.clone().readString(UTF8)+response.headers("Set-Cookie"));
            String session = response.headers("Set-Cookie").get(0);
            String cookie = session.substring(0, session.indexOf(";"));
            Log.d(TAG,cookie);
            if(cookie.startsWith("key=")) {
                UserConfig.getInstance(context).setCookie(cookie);
            }
        }
        return response;
    }
}
